<template>
<view>
		<view class="head">
			<navigator @click="gotoarrow" class="return-arrow">
				<image class="return-img" src="../../../static/arrow.png"></image>
			</navigator>
			<view class="service-list">预约列表</view>
		</view>
		<view class="tabs">
			  <view class="text-tab"
			  v-for="(item,index) in tabsParam"
			  @click="toggleTabs(index)">
			  <text 
			  :class="{active:index===nowIndex}">{{item}}</text> 
			  </view>
		 </view>
		<view class="page" id="pendding" v-show="nowIndex==0">
			<view v-if="reserve_list.length>0">
				<view class="list" v-for="(fmember, findex) in reserve_list">
						<img class="img-avatar" :src="fmember.service_img" >
						<p class="nane" >{{fmember.cardName}} <span class="view" @click="viewDetail(fmember)">查看</span></p>
						<p class="nane-small">用户名: {{fmember.userName}}</p>
						<button class="appointment" v-if="fmember.status==0 && fmember.serviceStartTime!=null"  @click="update_reserve(fmember.id,'end')">正在服务</button>
						<button class="appointment" v-if="fmember.status==0 && fmember.serviceStartTime==null" @click="update_reserve(fmember.id,'start')">开始服务</button>
						<p class="time">预约时间:<br /> {{fmember.serviceDate}} {{fmember.serviceHours}}</p>
						<p class="time"  v-if="fmember.status==1">服务时间: <br />{{fmember.serviceStartTime}}~{{fmember.serviceEndTime}}</p>
					</view>
			</view>
			<view v-else>
				<div class="no-result">暂无待处理预约数据！</div>
			</view>
		</view>

		<view class="page"  id="complated" v-show="nowIndex==1">
			<view v-if="reserve_list.length>0">
				<view class="list"  v-for="(fmember, findex) in reserve_list">
					<img class="img-avatar" :src="fmember.service_img" >
					<p class="nane">{{fmember.cardName}} 
					<!--<span class="view" @click="viewDetail(fmember)">查看</span> -->
					<span class="view" @click="goDetail(fmember)">查看</span>
					</p>
					<p class="nane-small">用户名: {{fmember.userName}}</p>
					<button class="appointment">已完成</button>
					<p class="time">预约时间:<br />  {{fmember.serviceDate}} {{fmember.serviceHours}}</p>
					<p class="time"  v-if="fmember.status==1">服务时间: <br />{{fmember.serviceStartTime}}~{{fmember.serviceEndTime}}</p>
				</view>
			</view>
			<view v-else>
				<div class="no-result">暂无已完成预约数据！</div>
			</view>
		</view>
		<view class="page"  id="admin_reserve" v-show="nowIndex==2">
			<view v-if="reserve_list.length>0">
				<view class="list"  v-for="(fmember, findex) in reserve_list">
					<img class="img-avatar" :src="fmember.service_img" >
					<p class="nane">{{fmember.cardName}} 
					<!--<span class="view" @click="viewDetail(fmember)">查看</span> -->
					<span class="view" @click="goDetail(fmember)">查看</span>
					</p>
					<p class="nane-small">用户名: {{fmember.userName}}</p><button class="appointment" v-if="fmember.status==0 "  @click="goDetail(fmember,'edit')">修改</button>
					<p class="nane-small">预约手机号: {{fmember.userPhone}}</p>
					<p class="nane-small">预约类型: {{fmember.froms}}</p>
					<p class="nane-small">美容师: {{fmember.shopUserName}}</p>
					
					<button class="appointment" v-if="fmember.status==0 && fmember.serviceStartTime!=null"  @click="update_reserve(fmember.id,'end')">正在服务</button>
					<button class="appointment" v-if="fmember.status==0 && fmember.serviceStartTime==null" @click="update_reserve(fmember.id,'start')">开始服务</button>
					<button class="appointment" v-if="fmember.status==1">已完成</button>
					<p class="time">预约时间:<br /> {{fmember.serviceDate}} {{fmember.serviceHours}}</p>
					<p class="time"  v-if="fmember.status==1">服务时间: <br />{{fmember.serviceStartTime}}~{{fmember.serviceEndTime}}</p>
				</view>
			</view>
			<view v-else>
				<div class="no-result">暂无店务预约数据！</div>
			</view>
		</view>
		<popup :open="openPopup" :position="position" :percent="percent" :background="background" @close="close">
			<view class="pop-detail">
				<p ><strong>使用卡项：</strong>{{use_card}}</p>
				<p ><strong>服务套餐：</strong>{{use_service}}</p>
			</view>
		</popup>
		<popup :open="openAdPopup" background="none" position="position" @close="close"></popup>
		
		<popup :open="openFile" :position="position" :percent="percent" :background="background" @close="closeFile" class="popup-file">
			<view class="pop-detail">
				  <div class="upload-info">
					  <text class="title_info">{{title_info}}</text>
					<div>
					<view v-for="pic in filePath"  class="picBox">
						<view class="remove-pic"  @click="removePic(pic)">X</view>
						<img class="pic-box" :src="pic">						
					</view>
					</div>
					<div style="clear: both;">
					<button type="primary" :loading="loading" @click="qupload">选择图片</button>
					<button type="primary" :loading="loading" @click="qsubmit">提交</button>
					<button type="info" @click="closeFile" style="background: #333 !important;">暂不上传</button>
					</div>
				  </div>
			</view>
		</popup>
</view>

</template>

<script>
import util from '@/common/util.js';
import popup from '@/components/YYT-popup/YYT-popup.vue';
import qiniuUploader from '@/components/qiniuUploader/qiniuUploader.js';
/*import Vue from 'vue'
import * as qiniu from 'qiniu-js';
import ElementUI from 'element-ui' //element-ui的全部组件
import 'element-ui/lib/theme-chalk/index.css'//element-ui的css
Vue.use(ElementUI) //使用elementUI
*/
export default {
	components: {
		popup,qiniuUploader
	},
	data() {
	    return{
	        tabsParam:['待处理','已完成','店务预约'],
	        nowIndex:0,
			reserve_list:[],
	        isShow:false,
			openPopup: false,
			position:"",
			background: '#fff',
			openAdPopup: false,
			openFile:false,
			percent: 0,
			showText: false,
			change: false,
			loopTimer: false,
			sizeSort: 'asc',
			use_service:"",
			use_card:"",
			loading: false,
			key: [], //图片名字处理
			token: [], //七牛云token
			domain: "https://upload-z2.qiniup.com", // 七牛云的上传地址（华南区）
			qiniuaddr: "http://images.common.think1st.cn", // 七牛云的图片外链地址
			uploadPicUrl: "", //提交到后台图片地址
			fileList: [],
			limit:3,
			rlId:'',
			imgType:'',
			title_info:'',
			filePath: [],
		}
	},
	onShow(){
		this.getReserveData(this.nowIndex==2 ?100:this.nowIndex);
	},
	mounted() {
		//this.getQiniuToken();
	},
	methods:{
		removePic(pic){
			var filePathNew=[]
			for (var i = 0; i < this.filePath.length; i++) {
				if(pic!=this.filePath[i]){
					filePathNew.push(this.filePath[i]);
				}
			}
			this.filePath=filePathNew;
		},
		qupload() {
			// 选择图片
			uni.chooseImage({
				count: 4,
				success: (res) => {
					this.filePath = this.filePath.concat(res.tempFilePaths);
					console.log(this.filePath);
					for (var i = 0; i < this.filePath.length; i++) {
						uni.request({
							url: 'https://emedia.sbedian.com/api/ability/getQiniuTokenInfo/common/ami_service',
							method: 'GET',
							header:{'content-type': 'application/x-www-form-urlencoded'},
							complete: (result) => {
								let tokenData = result.data;
								if (tokenData.code == "1") {
									this.token.push(tokenData.data.token);
									this.key.push(tokenData.data.name);
								}
							},
						});
					
					}
				}
			});
			
		},
		qsubmit() {//循环上传图片
			for (var i = 0; i < this.filePath.length; i++) {
				
				qiniuUploader.upload(this.filePath[i], (res) => {
					 this.addimgUrl(res.imageURL);
					console.log(res.imageURL);
				}, (error) => {
					var a = JSON.stringify(error);
					console.log('error: ' + a);
				}, {
					region: 'ECN',
					domain: this.qiniuaddr, // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
					key: this.key[i], // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
					// 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
					uptoken: this.token[i],
				});
			}
		},
		toggleTabs(index){
			if(this.nowIndex != index){
				this.nowIndex=index;
				this.getReserveData(index==2 ? 100:index);
			}
		     
		},
		gotoarrow(){
			this.$router.go(-1)
		},
		update_reserve(cid,type){
			var params={};
			if(type=='start'){
				params={id:cid,serviceStartTime:(new Date()).Format("yyyy-MM-dd hh:mm:ss")};
				this.title_info = '上传服务前的图片:'
			}else{
				params={id:cid,serviceEndTime:(new Date()).Format("yyyy-MM-dd hh:mm:ss"),status:1};
				this.title_info = '上传服务后的图片:'
			}
			this.position = 'ad';
			this.openFile =true;
			this.filePath=[];
			this.imgType=type;
			this.rlId = cid;
			//this.getQiniuToken();
			uni.request({
				url: uni.getStorageSync('api_url')+'/reserve/update',
				method: 'POST',
				data:params,
				header:{'content-type': 'application/x-www-form-urlencoded'},
				complete: (result) => {
					uni.hideLoading();
					if(result.data.code != 1){
						uni.showToast({
							title:result.data.msg,
							icon:'none'
						});
					}else{
						if(this.nowIndex==2){
							this.getReserveData(100);
						}else{	
							this.getReserveData(0);	
						}	
					}
					
				},
			});
		},
		navTo(url){
			//console.log(url);
			uni.navigateTo({
				url: url,
			})
		},
		viewDetail(item){
			this.use_service=item.serviceTitles;
			this.use_card=item.cardName;
			this.position = 'ad';
			this.openPopup = true;	
		},
		goDetail(item,type){
			uni.navigateTo({
				url: '/pages/home/reservation_list/reservation_detail/reservation_detail?reservation_data=' +JSON.stringify(item)+"&type="+type
			});
		},
		close(){
			this.openPopup=false;
		},
		closeFile(){
			this.openFile=false;
			this.uploadPicUrl = '';
		},
		getReserveData(status){
			
			var curTime = new Date();
			if(status==0){
					var newhours=curTime.setDate(curTime.getDate()+30);
					var startDate=(new Date()).Format("yyyy-MM-dd");
					var endDate=(new Date(newhours)).Format("yyyy-MM-dd");
					var where='shopId='+uni.getStorageSync('shop_id')+'&shopUserId='+uni.getStorageSync('admin_id')+'&status='+status+'&startDate='+startDate+'&endDate='+endDate;
			}else{
				var newhours=curTime.setDate(curTime.getDate()-30);
				var startDate=(new Date(newhours)).Format("yyyy-MM-dd");
				var endDate=(new Date()).Format("yyyy-MM-dd")
				var where='shopId='+uni.getStorageSync('shop_id')+'&shopUserId='+uni.getStorageSync('admin_id')+'&status='+status;
			}	
			this.reserve_list=[];
				uni.showLoading();
				uni.request({
					url: uni.getStorageSync('api_url')+'/reserve/getList?'+where,
					complete: (result) => {						
						if(result.data.code != 1){
							uni.hideLoading();
							uni.showToast({
								title:result.data.msg,
								icon:'none'
							});
						}else{
							uni.hideLoading();
							const data=result.data.data.data;
							data.forEach((rst) => {
								this.reserve_list.push(rst);	
							});							
						}						
					},
				});
			},
			handleRemove(file, fileList) {
			  this.uploadPicUrl = "";
			},
			handleExceed(files, fileList) {
			  this.$message.warning("当前限制选择"+this.limit+"张图片，如需更换，请删除上一张图片在重新选择!");
			},
			beforeAvatarUpload(file) {
			//	this.getQiniuToken();
			  const isPNG = file.type === "image/png";
			  const isJPEG = file.type === "image/jpeg";
			  const isJPG = file.type === "image/jpg";
			  const isLt2M = file.size / 1024 / 1024 < 2;
				
			  if (!isPNG && !isJPEG && !isJPG) {
				this.$message.error("上传图片只能是 jpg、png、jpeg 格式!");
				return false;
			  }
			  if (!isLt2M) {
				this.$message.error("上传图片大小不能超过 2MB!");
				return false;
			  }
			  //this.getQiniuToken();
			  //console.log(`upload_pic_${file.name}`);
			  //this.QiniuData.key = 'ami_service/'+`upload_pic_${file.name}`;
			},
			uploadSuccess(response, file, fileList) {
			  //console.log(fileList);
			  this.uploadPicUrl = `${this.qiniuaddr}/${response.key}`;
			  this.addimgUrl();
			},
			uploadError(err, file, fileList) {
			  this.$message({
				message: "上传出错，请重试！",
				type: "error",
				center: true
			  });
			},
			beforeRemove(file, fileList) {
			  // return this.$confirm(`确定移除 ${ file.name }？`);
			},
			//提交数据到后台
			handleSubmit() {
				 this.$refs.upload.submit();
			},
			addimgUrl(uploadPicUrl){
				uni.request({
					url: uni.getStorageSync('api_url')+'/reserve/addReImgUrl',
					method: 'POST',
					header:{'content-type': 'application/x-www-form-urlencoded'},
					data:{rlId:this.rlId,type:this.imgType,plUrl:uploadPicUrl,createUser:uni.getStorageSync('admin_name'),shoperId:uni.getStorageSync('admin_id'),shopId:uni.getStorageSync('shop_id')},
					complete: (result) => {					
						if(result.data.code!='1'){
							uni.showToast({
								title:result.data.msg,
								icon:'none'
							});
						}else{
							uni.showToast({
								title:'图片上传成功',
								icon:'none'
							});
							this.openFile=false;
							this.uploadPicUrl = '';
						}
						this.getRefImg();
					},
				});	
			},
			delReImgUrl(plId,plUrl){
				uni.showModal({
				    title: '确认',
				    content: '删除图片后无法恢复，确定要删除吗',
				    success: function (res) {
				        if (res.confirm) {
				            var plFile=plUrl.replace(this.qiniuaddr+'/','');
				            uni.request({
				            	url: uni.getStorageSync('api_url')+'/reserve/delReImgUrl',
				            	method: 'POST',
				            	header:{'content-type': 'application/x-www-form-urlencoded'},
				            	data:{plId:plId,plFile:plFile,admin_code:uni.getStorageSync('admin_code')},
				            	complete: (result) => {					
				            		if(result.data.code!='1'){
				            			uni.showToast({
				            				title:result.data.msg,
				            				icon:'none'
				            			});
				            		}else{
				            			uni.showToast({
				            				title:'图片删除成功',
				            				icon:'none'
				            			});
				            			this.getRefImg();
				            		}
				            		
				            	},
				            });	
				        }
				    }
				});
					
			}
	}
}	
</script>

<style>
.head{
	width: 100%;
	background-color: #ffffff;
	text-align: center;
	margin-bottom: 10px;
}
.service{
	width: 100%;
	height:2rem;
	border-radius:5px;
	background-color: #ffffff;
	margin-bottom: 1rem;
	font-size: 0.8rem;
}
.data-list{
	float: left;
	margin: 8px 0 0 15px;
}
.arrows{
	float: right;
	margin: 8px 15px 0 0;
}
.tabs{
	    
	    width: 100%;
	    font-size: 16px;
	    line-height: 16px;
	    display: flex;
		height: 35px;
	    justify-content: space-around;
}
.page{position: relative;}
	.text-tab{
		pointer-events: auto;
		    width: 50%;
		    float: left;
		    text-align: center;
	margin-bottom: 10px;
	}
.active{		   
		border-bottom: 2px solid #6d1c79;
	}
button{
	color: #ffffff;
	background-color: #6d1c79;
	}
.appointment{
	font-size: 12px;
	line-height: 30px;
	padding: 0 8px !important;
	height: 30px;
	float: right;
	margin-bottom: 5px;
	background: #6d1c79;
	}
.appointment2{
		width: 20%;
		font-size: 12px;
		line-height: 30px;
		padding: 0 8px !important;
		height: 30px;
		background: #6d1c79;
		float: right;
		margin-bottom: 5px;
	}
.nane{
	float: left;
	width:65%;
	font-size: 14px;
	line-height: 30px;
	margin-left: 5%;
	}
.pop-detail{font-size: 14px;line-height: 20px;}
.nane .view{
		margin-left: 10px;
		padding: 3px 5px;
		color:#661F73 ;
		font-weight: bold;
		text-decoration: underline;
	}
.nane-small{
		float: left;
		width:70%;
		font-size: 14px;
		line-height: 30px;
		margin-left: 5%;
	}
.time{  margin-left:5%;  float: left; font-size: 14px;
	}
.img-avatar{
		width: 25%;
		border-radius: 50%;
		float: left;
	}
.list{
		display: inline-block;
		font-size: 0.8rem;
		border-radius: 5px;
		padding: 10px;
		margin-bottom: 1rem;
		background: #fffcfe;
	}
.no-result {
		text-align: center;
		font-size: 16px;
	}
.title_info {
	    font-size: 20px;
	    margin-bottom: 10px;
	    display: block;
	    padding: 20px;
	    padding-left: 10px;
	    font-weight: bold;
}
.upload-info button{width: 47%; float:left; margin: 3% 1.5%;}
	.picBoxShow{position: relative;
	    display: inline-block;
		width: 98%;margin:2% auto; text-align: center;}
		.picBoxShow img{max-width: 100%;}
	.picBox{position: relative;
		width: 46%;margin:2%;float:left;
	}
	.picBox img{max-width: 100%;max-height: 200px;}
	.picBox .remove-pic,.picBoxShow .remove-pic{
		position: absolute;
		top: 0;
		right: 0;
		width: 25px;
		height: 25px;
		font-size: 16px;
		line-height: 25px;
		text-align: center;
		color: #fff;
		background: #00C971;	
	}
</style>
